# -*- coding: utf-8 -*-
"""
Created on Wed Jul 31 13:03:39 2013

@author: Jeanhwea
"""
from urllib2 import urlopen
from socket import setdefaulttimeout
from time import sleep
from time import time, localtime, strftime
import os, sys
''' some macros
'''
url = 'http://www.icbc.com.cn/FinanceMarket/gold/Default.aspx'
_id = 'ctl00_Content_Boby_AccountGold1_Label_mrj1'
sleepTime = 10
soldprice = 274.41
quantity = 42

def main():
    setdefaulttimeout(sleepTime)
    while True:
        try:
            res = urlopen(url)
            html = res.read()
            index = html.find(_id)
            start = index + len(_id) + 17
            price = float(html[start:start+6])
            
            ''' If you install BeautifulSoup, a better way to check price like this:
            from BeautifulSoup import BeautifulSoup
            soup = BeautifulSoup(html)
            price = float(soup.findAll(id = _id)[0].font.text[:5])
            '''            
            
            # print html[start:start+6]
            currentTime = strftime('"time":"%H:%M:%S", "date":"%Y-%m-%d"',localtime(time()))
            net =  (price - soldprice) * quantity
            print '{"price":%.2f, %s, "net":%.2f}' %(price, currentTime, net)
            sys.stdout.flush()
#            if net < 0:
#                os.system("rhythmbox")
#                break
            sleep(sleepTime)
            #return
        except :
            print '{"price": 0, "time":"0:0:0", "date":"2013-08-01", "net":-1}'
            sys.stdout.flush()
        

if __name__ == '__main__':
    main()
